package net.cyue.ort.llm.gui.chat;

import javax.swing.*;
import java.awt.*;

/**
 * 左侧聊天区域的具体实现，负责展示会话内容并将用户输入交给 {@link ChatController}。
 */
public class ChatPanel extends JPanel implements ChatView {

    private final JTextArea transcriptArea = new JTextArea();
    private final JTextField inputField = new JTextField();
    private final ChatController controller;

    public ChatPanel(JFrame frame, ChatController controller) {
        super(new BorderLayout());
        this.controller = controller;
        controller.attachView(this);

        setPreferredSize(new Dimension(frame.getWidth() * 2 / 3, frame.getHeight()));

        transcriptArea.setEditable(false);
        transcriptArea.setFont(new Font("宋体", Font.PLAIN, 14));
        transcriptArea.setLineWrap(true);
        transcriptArea.setWrapStyleWord(true);
        transcriptArea.setText("System: 欢迎使用ORT，请先选择并加载模型\n");

        JScrollPane scrollPane = new JScrollPane(transcriptArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        inputField.addActionListener(e -> this.controller.handleUserInput(inputField.getText()));

        add(scrollPane, BorderLayout.CENTER);
        add(inputField, BorderLayout.SOUTH);
    }

    @Override
    public void showSystemMessage(String message) {
        appendLine("System", message);
    }

    @Override
    public void showUserMessage(String message) {
        appendLine("User", message);
    }

    @Override
    public void beginAssistantResponse() {
        append("Assistant: ");
    }

    @Override
    public void appendAssistantResponse(String chunk) {
        append(chunk);
    }

    @Override
    public void endAssistantResponse() {
        append("\n");
    }

    @Override
    public void clearInput() {
        SwingUtilities.invokeLater(() -> inputField.setText(""));
    }

    @Override
    public void setInputEnabled(boolean enabled) {
        SwingUtilities.invokeLater(() -> inputField.setEnabled(enabled));
    }

    private void appendLine(String role, String message) {
        append(role + ": " + message + "\n");
    }

    private void append(String content) {
        SwingUtilities.invokeLater(() -> transcriptArea.append(content));
    }
}

